package android.slc.appbase.ui.utils;

import android.app.Dialog;
import android.slc.appbase.R;
import android.slc.popup.SlcPopup2;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.StringRes;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.StringUtils;

public class LoadingUtils {
    private static final String KEY_PRESENTER_DIALOG = "loadingDialog";

    public static void showLoadingDialog(String loadingMsg) {
        showLoadingDialog(KEY_PRESENTER_DIALOG, loadingMsg);
    }

    public static void showLoadingDialog(String key, String loadingMsg) {
        SlcPopup2.createLoadingDialogOperate().setKey(key).setCancelable(false).show(createLoadingDialog(loadingMsg));
    }

    public static void showLoadingDialog(@StringRes int loadingRes) {
        showLoadingDialog(KEY_PRESENTER_DIALOG, loadingRes);
    }

    public static void showLoadingDialog(String key, @StringRes int loadingRes) {
        SlcPopup2.createLoadingDialogOperate().setKey(key).setCancelable(false).show(createLoadingDialog(loadingRes));
    }

    public static void dismissLoadingDialog() {
        dismissLoadingDialog(KEY_PRESENTER_DIALOG);
    }

    public static void dismissLoadingDialog(String key) {
        SlcPopup2.dismissByKey(key);
    }

    private static Dialog createLoadingDialog(@StringRes int loadingMsg) {
        return createLoadingDialog(StringUtils.getString(loadingMsg));
    }

    private static Dialog createLoadingDialog(String loadingMsg) {
        int maxWidth = 0;
        int maxHeight = 0;
        Dialog loadingDialog = new Dialog(ActivityUtils.getTopActivity(), 0);
        View loadingView = LayoutInflater.from(ActivityUtils.getTopActivity()).inflate(R.layout.slc_popup_def_loading, (ViewGroup) null);

        TextView messageTextView = (TextView) loadingView.findViewById(android.R.id.message);
        if (messageTextView != null) {
            messageTextView.setText(loadingMsg);
        }

        loadingDialog.setContentView(loadingView);
        loadingDialog.getWindow().getDecorView().addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
            ViewGroup.LayoutParams contentViewLayoutParams = v.getLayoutParams();
            if (contentViewLayoutParams != null) {
                if (maxWidth != 0 && v.getWidth() > maxWidth) {
                    contentViewLayoutParams.width = maxWidth;
                }

                if (maxHeight != 0 && v.getHeight() > maxHeight) {
                    contentViewLayoutParams.height = maxHeight;
                }

                v.setLayoutParams(contentViewLayoutParams);
            }

        });
        return loadingDialog;
    }
}
